package java_thinking.unit_21._21_4;

import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;

/**
 * @Desc:   4-1 使用java监视器模式的线程安全计数器 如Vector Hashtable
 * @author: cww
 * @DateTime: 2019-06-01 23:56
 */
@ThreadSafe
public class Counter {
    @GuardedBy("this") private long value = 0;
    public synchronized long getValue() {
        return value;
    }
    public synchronized long increment() throws IllegalAccessException {
        if (value == Long.MAX_VALUE) {
            throw new IllegalAccessException("counter overflow");
        } else {
            return ++value;
        }
    }
}

class Test {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    counter.increment();
                    counter.increment();
                    System.out.println(counter.getValue());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread.sleep(3000);
        long s = counter.getValue();
        System.out.println(s);
    }
}